package Monitor

import (
	"encoding/json"
	"fmt"
	"io"
	"log"
	"log_process/system"
	"log_process/service/Process"
	"net/http"
	"time"
)

//SystemInfo 系统运行信息
type SystemInfo struct {
	HandleLine   int     `json:"handleLine"`   //总处理日志行数
	Tps          float64 `json:"tps"`          //系统吞吐量
	ReadChanLen  int     `json:"readChanLen"`  //read channel 长度
	WriteChanLen int     `json:"writeChanLen"` //write channel 长度
	RunTime      string  `json:"runTime"`      //系统运行时间
	ErrNum       int     `json:"errNum"`       //错误数量
}

type Monitor struct {
	StartTime time.Time
	Data      SystemInfo
	TpsSli    []int
}


func (m *Monitor) Start(lg *Process.LogProcess, addr string) {

	go func() {

		var (
			v int
		)

		for v = range system.TypeMonitorChan {
			switch v {
			case system.TypeHandleLine:
				m.Data.HandleLine += 1
			case system.TypeErrNum:
				m.Data.ErrNum += 1
			}
		}
	}()

	ticker := time.NewTicker(time.Second * 5)

	go func() {
		for {
			<-ticker.C
			m.TpsSli = append(m.TpsSli, m.Data.HandleLine)
			if len(m.TpsSli) > 2 {
				m.TpsSli = m.TpsSli[1:]
			}
		}
	}()

	http.HandleFunc("/monitor", func(writer http.ResponseWriter, request *http.Request) {
		var (
			res []byte
			err error
		)

		m.Data.RunTime = time.Now().Sub(m.StartTime).String()
		m.Data.ReadChanLen = len(lg.ReadChan)
		m.Data.WriteChanLen = len(lg.WriteChan)

		if len(m.TpsSli) == 2 {
			m.Data.Tps = float64(m.TpsSli[1]-m.TpsSli[0]) / 5
		}

		if res, err = json.MarshalIndent(m.Data, "", "\t"); err != nil {
			log.Println(fmt.Sprintf("MarshalIndent error：%s", err.Error()))
			return
		}

		if _, err = io.WriteString(writer, string(res)); err != nil {
			log.Println(fmt.Sprintf("WriteString error：%s", err.Error()))
		}
	})

	_ = http.ListenAndServe(addr, nil)
}
